/*
 * @Author: sundeqi
 * @Date: 2021-10-11 17:26:33
 * @LastEditors: sundeqi
 * @LastEditTime: 2022-03-23 11:40:36
 * @Description: 公用类基础工具
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show SystemChannels;
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'log_util.dart';

class PlatformUtil {
  // 通过kIsWeb变量判断是否为web环境!
  static bool get isWeb => kIsWeb == true;

  static bool get isAndroid => isWeb ? false : Platform.isAndroid;

  static bool get isIOS => isWeb ? false : Platform.isIOS;
}

class CommonUtil {
  static String imgUrl(String url) {
    // return url;
    if (url.isEmpty) {
      LogUtil.e(msg: 'url 不能为空');
      return '';
    }
    if (url.contains('https:') || url.contains('http:')) return url;
    return "https:" + url;
  }

  static Size calculateTextSize(BuildContext context, String value,
      {double fontSize = 13,
      FontWeight fontWeight = FontWeight.normal,
      double? maxWidth,
      int maxLines = 1}) {
    maxWidth = maxWidth ?? MediaQuery.of(context).size.width;
    TextPainter painter = TextPainter(

        ///AUTO：华为手机如果不指定locale的时候，该方法算出来的文字高度是比系统计算偏小的。
        locale: Localizations.localeOf(context),
        maxLines: maxLines,
        textDirection: TextDirection.ltr,
        text: TextSpan(
            text: value,
            style: TextStyle(
              fontWeight: fontWeight,
              fontSize: fontSize,
            )));
    painter.layout(maxWidth: maxWidth);

    ///文字的宽度:painter.width
    return painter.size;
  }

  ///具体可看：TextInputChannel
  static void hideKeyboard() {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  ///具体可看：TextInputChannel
  static void showKeyboard() {
    SystemChannels.textInput.invokeMethod('TextInput.show');
  }

  /// 清除数据
  static void clearClientKeyboard() {
    SystemChannels.textInput.invokeMethod('TextInput.clearClient');
  }

  static void clearFocus(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }
}
